﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ADUSWebApp.Models;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Web.Routing;
using ADUSWebApp.DBConnect;


namespace ADUSWebApp.Controllers
{
    public class UserController : Controller
    {
        //接口
        public Models.IFormsApplyService FormsService { get; set; }
        SqlHelper dbhelp = new SqlHelper();

        /// <summary>
        /// 重载初始化
        /// </summary>
        /// <param name="requestContext"></param>
        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null)
            {
                FormsService = new FormsApplyService();
            }
            base.Initialize(requestContext);
        }

        public ActionResult Index()
        {
            return View();
        }


        public ActionResult LoginPage()
        {
            ViewData["Message"] = "欢迎来到翼的 LoginPage!";

            return View();
        }

        public ActionResult LoginWelcome()
        {
            ViewData["Message"] = "欢迎来到翼的 LoginWelcome!";

            return View();
        }

        ///
        /// 判断user是否成功登陆
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginModel login)
        {
            bool isLogin;
            isLogin = dbhelp.UserLogin(login);
            if (isLogin)
            {
                //如果用户名存在，转向主页
                FormsService.SignIn(login.UserName, login.Remember);
                return View("LoginWelcome");
            }
            else
            {
                //登录失败，转向登录页面
                ModelState.AddModelError("", "用户名或者密码不正确.");
                return View();
            }
        }

        public ActionResult Loginout()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        ///
        ///判断user是否存在
        ///
        public ActionResult UserExist()
        {
            //查询出所有用户
            DataSet ds = dbhelp.GetAllUsers();
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                List<Models.UserModel> lists = new List<Models.UserModel>();

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    UserModel usermodel = new UserModel();
                    usermodel.LoginName = ds.Tables[0].Rows[i]["UserName"].ToString();
                    usermodel.LoginPassword = ds.Tables[0].Rows[i]["UserPwd"].ToString();
                    usermodel.Email = ds.Tables[0].Rows[i]["Email"].ToString();
                    lists.Add(usermodel);
                }
                if (lists.Count > 0)
                {
                    ViewData["users"] = lists;
                }
            }
            return View();
        }

        //
        // GET: /User/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        /// <summary>
        /// 注册账号
        /// </summary>
        /// <returns></returns>

        public ActionResult Enroll()
        {
            return View();
        }

        //
        // POST: /User/Enroll

        [HttpPost]
        public ActionResult Enroll(UserModel usermodel)
        {
            try
            {
                // TODO: Add insert logic here
                if (ModelState.IsValid)
                {
                    bool ifExist;
                    bool ifEnroll;
                    ifExist = dbhelp.ExistUser(usermodel);
                    if (ifExist)
                    {
                        ModelState.AddModelError("", "用户名已存在.");
                        return RedirectToAction("Index");
                    }
                    else
                    {
                        ifEnroll = dbhelp.AddUser(usermodel);
                        return View("EnrollOK");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "添加用户失败.");
                    return View();
                }
                //return RedirectToAction("Index", "Home");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /User/Edit/5

        public ActionResult EditUser(string userName)
        {
            // 根据用户名获取用户信息
            DataSet ds = dbhelp.GetSingleUser(userName);
            return View();
        }

        /// <summary>
        /// 转向编辑页面
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditUser()
        {
            try
            {
                string userName = Request.QueryString["userName"].ToString();
                string userPassword = Request.Form["userPassword"].ToString();
                string userEmail = Request.Form["userEmail"].ToString();
                bool isEditUser;
                if (userName == "" || userPassword == "")
                {
                    ViewData["errMsg"] = "用户名和密码不能为空";
                    return EditUser(userName);
                }
                else
                {
                    isEditUser = dbhelp.EditUser(userName, userPassword, userEmail);
                }
                if (isEditUser)
                {
                    return View("EditUserOK");
                }
                else
                {
                    ModelState.AddModelError("", "修改用户失败.");
                    return View();
                }
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /User/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /User/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
